package com.xinlong.shop.api.member;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinlong.shop.api.common.BuyerBaseController;
import com.xinlong.shop.core.member.entity.MemberWithdrawal;
import com.xinlong.shop.core.member.service.IMemberService;
import com.xinlong.shop.core.member.service.IMemberWithdrawalService;
import com.xinlong.shop.framework.common.R;
import com.xinlong.shop.framework.core.entity.Member;
import com.xinlong.shop.framework.security.constant.SecurityConstants;
import com.xinlong.shop.framework.security.util.TokenUtil;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;

/**
 * @Author Sylow
 * @Description 会员提现记录
 * @Date: Created in 00:18 2023/04/07
 */
@RestController
@RequestMapping("/buyer/member/withdrawal")
public class BuyerWithdrawalControllerBuyer extends BuyerBaseController {

    private final IMemberWithdrawalService memberWithdrawalService;

    public BuyerWithdrawalControllerBuyer(IMemberService memberService, TokenUtil tokenUtil, IMemberWithdrawalService memberWithdrawalService) {
        super(memberService, tokenUtil);
        this.memberWithdrawalService = memberWithdrawalService;
    }

    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public R page(Integer current, Integer size, @RequestHeader(value = SecurityConstants.TOKEN_HEADER, required = true) String token){
        Page<MemberWithdrawal> page = new Page<>(current, size);
        Member member = getMember(token);
        page = this.memberWithdrawalService.page(page, member.getId());
        return R.success("操作成功", page);
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    public R add(@Valid @RequestBody MemberWithdrawal memberWithdrawal, @RequestHeader(value = SecurityConstants.TOKEN_HEADER, required = true) String token){

        //等于 -1就是小于
        if (memberWithdrawal.getPrice().compareTo(BigDecimal.valueOf(100)) == -1) {
            return R.error("提现金额至少100元");
        }

        Member member = getMember(token);

        // 如果余额小于提现金额
        if (member.getBalance().compareTo(memberWithdrawal.getPrice()) == -1) {
            return R.error("余额不足");
        }

        memberWithdrawal.setMemberId(member.getId());
        memberWithdrawal.setCreateTime(DateUtil.currentSeconds());

        this.memberWithdrawalService.add(memberWithdrawal);
        return R.success("操作成功");


    }

}
